#!/usr/bin/perl
#
# Merge entries from 2 users
# as far as possible
#
use strict;
use Counter;
use Fcntl;
use Getopt::Long;

use vars qw($k1 $k2 $users $r1 $r2 $testmode $revmode $emptyok);

GetOptions("revok" => \$revmode,
	   "test|n" => \$testmode,
	   "emptyok" => \$emptyok,
	   );

my $k1 = shift;
my $k2 = shift;

if (($k1 > $k2) && !$revmode) {
    die "Are you sure you don't mean $0 $k2 $k1?\n";
}

$users = Counter::open(O_RDWR);
if ($emptyok) {
    $r1 = $users->get($k1, O_CREAT);
} else {
    $r1 = $users->get($k1);
}
$r2 = $users->get($k2);

die "$k1 is not a valid key\n" if !$r1 && !$emptyok;
die "$k2 is not a valid key\n" if !$r2;

if ($r1) {
    print "R1: $$r1{email}\n";
    print "Machines: ", $r1->machines() + 0, "\n";
    print "Emails: ", $r1->emails() + 0, "\n";
    print "Friends: ", $r1->friends() + 0, "\n";
    print "Records: ", $r1->ownedrecs() + 0, "\n";
} else {
    print "No R1\n";
}
print "R2: $$r2{email}\n";
print "Machines: ", $r2->machines() + 0, "\n";
print "Emails: ", $r2->emails() + 0, "\n";
print "Friends: ", $r2->friends() + 0, "\n";
print "Records: ", $r2->ownedrecs() + 0, "\n";



movesubrecs();

mergerecs($r1->person(O_CREAT), $r2->person(), "person") if $r2->person();
mergerecs($r1, $r2, "user");


sub movesubrecs {
    my $subrec;

    for $subrec ($r2->ownedrecs()) {
	$subrec->{owner} = $r1->key();
	$subrec->store() if !$testmode;
    }
}

sub mergerecs {
    my $p1 = shift;
    my $p2 = shift;
    my $what = shift;
    my $field;
    my $changes;

    return if !$p2;
    die "Cannot merge to empty\n" if !$p1;
    for $field ($p2->fields()) {
	if ($p1->{$field} && $p2->{$field} ne $p1->{$field}) {
	    print "Difference $what $field: p1 $$p1{$field} p2 $$p2{$field}\n";
	} elsif (!$p1->{$field}) {
	    print "Adding to p1 $what: $field: $$p2{$field}\n";
	    $p1->{$field} = $p2->{$field};
	    ++ $changes;
	}
    }
    $p1->store() if $changes && !$testmode;
    $p2->delete() if !$testmode;
}


